<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      34-反射 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>34-反射</h2>



  <p class="post-date">2019-03-10</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><p>反射是 Go 语言的高级主题之一。</p>
<p>分为如下小节。</p>
<ul>
<li>什么是反射？</li>
<li>为何需要检查变量，确定变量的类型？</li>
<li>reflect 包<ul>
<li>reflect.Type 和 reflect.Value</li>
<li>reflect.Kind</li>
<li>NumField() 和 Field() 方法</li>
<li>Int() 和 String() 方法</li>
</ul>
</li>
<li>完整的程序</li>
<li>我们应该使用反射吗？</li>
</ul>
<h2 id="什么是反射？"><a href="#什么是反射？" class="headerlink" title="什么是反射？"></a>什么是反射？</h2><p>反射就是程序能够在运行时检查变量和值，求出它们的类型。你可能还不太懂，这没关系。在本教程结束后，你就会清楚地理解反射，所以跟着我们的教程学习吧。</p>
<h2 id="为何需要检查变量，确定变量的类型？"><a href="#为何需要检查变量，确定变量的类型？" class="headerlink" title="为何需要检查变量，确定变量的类型？"></a>为何需要检查变量，确定变量的类型？</h2><p>在学习反射时，所有人首先面临的疑惑就是：如果程序中每个变量都是我们自己定义的，那么在编译时就可以知道变量类型了，为什么我们还需要在运行时检查变量，求出它的类型呢？没错，在大多数时候都是这样，但并非总是如此。</p>
<p>我来解释一下吧。下面我们编写一个简单的程序。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    i := <span class="number">10</span></span><br><span class="line">    fmt.Printf(<span class="string">"%d %T"</span>, i, i)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，<code>i</code> 的类型在编译时就知道了，然后我们在下一行打印出 <code>i</code>。这里没什么特别之处。</p>
<p>现在了解一下，需要在运行时求得变量类型的情况。假如我们要编写一个简单的函数，它接收结构体作为参数，并用它来创建一个 SQL 插入查询。</p>
<p>考虑下面的程序：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    o := order&#123;</span><br><span class="line">        ordId:      <span class="number">1234</span>,</span><br><span class="line">        customerId: <span class="number">567</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(o)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，我们需要编写一个函数，接收结构体变量 <code>o</code> 作为参数，返回下面的 SQL 插入查询。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into order values(1234, 567)</span><br></pre></td></tr></table></figure>

<p>这个函数写起来很简单。我们现在编写这个函数。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">createQuery</span><span class="params">(o order)</span> <span class="title">string</span></span> &#123;</span><br><span class="line">    i := fmt.Sprintf(<span class="string">"insert into order values(%d, %d)"</span>, o.ordId, o.customerId)</span><br><span class="line">    <span class="keyword">return</span> i</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    o := order&#123;</span><br><span class="line">        ordId:      <span class="number">1234</span>,</span><br><span class="line">        customerId: <span class="number">567</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(createQuery(o))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第 12 行，<code>createQuery</code> 函数用 <code>o</code> 的两个字段（<code>ordId</code> 和 <code>customerId</code>），创建了插入查询。该程序会输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into order values(1234, 567)</span><br></pre></td></tr></table></figure>

<p>现在我们来升级这个查询生成器。如果我们想让它变得通用，可以适用于任何结构体类型，该怎么办呢？我们用程序来理解一下。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> employee <span class="keyword">struct</span> &#123;</span><br><span class="line">    name <span class="keyword">string</span></span><br><span class="line">    id <span class="keyword">int</span></span><br><span class="line">    address <span class="keyword">string</span></span><br><span class="line">    salary <span class="keyword">int</span></span><br><span class="line">    country <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">createQuery</span><span class="params">(q <span class="keyword">interface</span>&#123;&#125;)</span> <span class="title">string</span></span> &#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们的目标就是完成 <code>createQuery</code> 函数（上述程序中的第 16 行），它可以接收任何结构体作为参数，根据结构体的字段创建插入查询。</p>
<p>例如，如果我们传入下面的结构体：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">o := order &#123;</span><br><span class="line">    ordId: <span class="number">1234</span>,</span><br><span class="line">    customerId: <span class="number">567</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>createQuery</code> 函数应该返回：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into order values (1234, 567)</span><br></pre></td></tr></table></figure>

<p>类似地，如果我们传入：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">e := employee &#123;</span><br><span class="line">       name: <span class="string">"Naveen"</span>,</span><br><span class="line">       id: <span class="number">565</span>,</span><br><span class="line">       address: <span class="string">"Science Park Road, Singapore"</span>,</span><br><span class="line">       salary: <span class="number">90000</span>,</span><br><span class="line">       country: <span class="string">"Singapore"</span>,</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>该函数会返回：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into employee values(&quot;Naveen&quot;, 565, &quot;Science Park Road, Singapore&quot;, 90000, &quot;Singapore&quot;)</span><br></pre></td></tr></table></figure>

<p>由于 <code>createQuery</code> 函数应该适用于任何结构体，因此它接收 <code>interface{}</code> 作为参数。为了简单起见，我们只处理包含 <code>string</code> 和 <code>int</code> 类型字段的结构体，但可以扩展为包含任何类型的字段。</p>
<p><code>createQuery</code> 函数应该适用于所有的结构体。因此，要编写这个函数，就必须在运行时检查传递过来的结构体参数的类型，找到结构体字段，接着创建查询。这时就需要用到反射了。在本教程的下一步，我们将会学习如何使用 <code>reflect</code> 包来实现它。</p>
<h2 id="reflect-包"><a href="#reflect-包" class="headerlink" title="reflect 包"></a>reflect 包</h2><p>在 Go 语言中，<code>reflect</code>实现了运行时反射。<code>reflect</code> 包会帮助识别 <code>interface{}</code>变量的底层具体类型和具体值。这正是我们所需要的。<code>createQuery</code> 函数接收 <code>interface{}</code> 参数，根据它的具体类型和具体值，创建 SQL 查询。这正是 <code>reflect</code> 包能够帮助我们的地方。</p>
<p>在编写我们通用的查询生成器之前，我们首先需要了解 <code>reflect</code> 包中的几种类型和方法。让我们来逐个了解。</p>
<h3 id="reflect-Type-和-reflect-Value"><a href="#reflect-Type-和-reflect-Value" class="headerlink" title="reflect.Type 和 reflect.Value"></a>reflect.Type 和 reflect.Value</h3><p><code>reflect.Type</code> 表示 <code>interface{}</code> 的具体类型，而 <code>reflect.Value</code> 表示它的具体值。<code>reflect.TypeOf()</code> 和 <code>reflect.ValueOf()</code> 两个函数可以分别返回 <code>reflect.Type</code> 和 <code>reflect.Value</code>。这两种类型是我们创建查询生成器的基础。我们现在用一个简单的例子来理解这两种类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"reflect"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">createQuery</span><span class="params">(q <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">    t := reflect.TypeOf(q)</span><br><span class="line">    v := reflect.ValueOf(q)</span><br><span class="line">    fmt.Println(<span class="string">"Type "</span>, t)</span><br><span class="line">    fmt.Println(<span class="string">"Value "</span>, v)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    o := order&#123;</span><br><span class="line">        ordId:      <span class="number">456</span>,</span><br><span class="line">        customerId: <span class="number">56</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    createQuery(o)</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，第 13 行的 <code>createQuery</code> 函数接收 <code>interface{}</code> 作为参数。在第 14 行，<code>reflect.TypeOf</code> 接收了参数 <code>interface{}</code>，返回了<code>reflect.Type</code>，它包含了传入的 <code>interface{}</code> 参数的具体类型。同样地，在第 15 行，<code>reflect.ValueOf</code>函数接收参数 <code>interface{}</code>，并返回了 <code>reflect.Value</code>，它包含了传来的 <code>interface{}</code> 的具体值。</p>
<p>上述程序会打印：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Type  main.order</span><br><span class="line">Value  &#123;456 56&#125;</span><br></pre></td></tr></table></figure>

<p>从输出我们可以看到，程序打印了接口的具体类型和具体值。</p>
<h3 id="relfect-Kind"><a href="#relfect-Kind" class="headerlink" title="relfect.Kind"></a>relfect.Kind</h3><p><code>reflect</code> 包中还有一个重要的类型：<code>Kind</code>。</p>
<p>在反射包中，<code>Kind</code> 和 <code>Type</code> 的类型可能看起来很相似，但在下面程序中，可以很清楚地看出它们的不同之处。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"reflect"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">createQuery</span><span class="params">(q <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">    t := reflect.TypeOf(q)</span><br><span class="line">    k := t.Kind()</span><br><span class="line">    fmt.Println(<span class="string">"Type "</span>, t)</span><br><span class="line">    fmt.Println(<span class="string">"Kind "</span>, k)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    o := order&#123;</span><br><span class="line">        ordId:      <span class="number">456</span>,</span><br><span class="line">        customerId: <span class="number">56</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    createQuery(o)</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上述程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Type  main.order</span><br><span class="line">Kind  struct</span><br></pre></td></tr></table></figure>

<p>我想你应该很清楚两者的区别了。<code>Type</code> 表示 <code>interface{}</code> 的实际类型（在这里是 <strong>main.Order</strong>)，而 <code>Kind</code> 表示该类型的特定类别（在这里是 <strong>struct</strong>）。</p>
<h3 id="NumField-和-Field-方法"><a href="#NumField-和-Field-方法" class="headerlink" title="NumField() 和 Field() 方法"></a>NumField() 和 Field() 方法</h3><p><code>NumField()</code>方法返回结构体中字段的数量，而 <code>Field(i int)</code>方法返回字段 <code>i</code> 的 <code>reflect.Value</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"reflect"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">createQuery</span><span class="params">(q <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">    <span class="keyword">if</span> reflect.ValueOf(q).Kind() == reflect.Struct &#123;</span><br><span class="line">        v := reflect.ValueOf(q)</span><br><span class="line">        fmt.Println(<span class="string">"Number of fields"</span>, v.NumField())</span><br><span class="line">        <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; v.NumField(); i++ &#123;</span><br><span class="line">            fmt.Printf(<span class="string">"Field:%d type:%T value:%v\n"</span>, i, v.Field(i), v.Field(i))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    o := order&#123;</span><br><span class="line">        ordId:      <span class="number">456</span>,</span><br><span class="line">        customerId: <span class="number">56</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    createQuery(o)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的程序中，因为 <code>NumField</code> 方法只能在结构体上使用，我们在第 14 行首先检查了 <code>q</code> 的类别是 <code>struct</code>。程序的其他代码很容易看懂，不作解释。该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Number of fields 2</span><br><span class="line">Field:0 type:reflect.Value value:456</span><br><span class="line">Field:1 type:reflect.Value value:56</span><br></pre></td></tr></table></figure>

<h3 id="Int-和-String-方法"><a href="#Int-和-String-方法" class="headerlink" title="Int() 和 String() 方法"></a>Int() 和 String() 方法</h3><p><code>Int</code>和 <code>String</code>可以帮助我们分别取出 <code>reflect.Value</code> 作为 <code>int64</code> 和 <code>string</code>。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"reflect"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    a := <span class="number">56</span></span><br><span class="line">    x := reflect.ValueOf(a).Int()</span><br><span class="line">    fmt.Printf(<span class="string">"type:%T value:%v\n"</span>, x, x)</span><br><span class="line">    b := <span class="string">"Naveen"</span></span><br><span class="line">    y := reflect.ValueOf(b).String()</span><br><span class="line">    fmt.Printf(<span class="string">"type:%T value:%v\n"</span>, y, y)</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面程序中的第 10 行，我们取出 <code>reflect.Value</code>，并转换为 <code>int64</code>，而在第 13 行，我们取出 <code>reflect.Value</code> 并将其转换为 <code>string</code>。该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">type:int64 value:56</span><br><span class="line">type:string value:Naveen</span><br></pre></td></tr></table></figure>

<h2 id="完整的程序"><a href="#完整的程序" class="headerlink" title="完整的程序"></a>完整的程序</h2><p>现在我们已经具备足够多的知识，来完成我们的查询生成器了，我们来实现它把。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"reflect"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> order <span class="keyword">struct</span> &#123;</span><br><span class="line">    ordId      <span class="keyword">int</span></span><br><span class="line">    customerId <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> employee <span class="keyword">struct</span> &#123;</span><br><span class="line">    name    <span class="keyword">string</span></span><br><span class="line">    id      <span class="keyword">int</span></span><br><span class="line">    address <span class="keyword">string</span></span><br><span class="line">    salary  <span class="keyword">int</span></span><br><span class="line">    country <span class="keyword">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">createQuery</span><span class="params">(q <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">    <span class="keyword">if</span> reflect.ValueOf(q).Kind() == reflect.Struct &#123;</span><br><span class="line">        t := reflect.TypeOf(q).Name()</span><br><span class="line">        query := fmt.Sprintf(<span class="string">"insert into %s values("</span>, t)</span><br><span class="line">        v := reflect.ValueOf(q)</span><br><span class="line">        <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; v.NumField(); i++ &#123;</span><br><span class="line">            <span class="keyword">switch</span> v.Field(i).Kind() &#123;</span><br><span class="line">            <span class="keyword">case</span> reflect.Int:</span><br><span class="line">                <span class="keyword">if</span> i == <span class="number">0</span> &#123;</span><br><span class="line">                    query = fmt.Sprintf(<span class="string">"%s%d"</span>, query, v.Field(i).Int())</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    query = fmt.Sprintf(<span class="string">"%s, %d"</span>, query, v.Field(i).Int())</span><br><span class="line">                &#125;</span><br><span class="line">            <span class="keyword">case</span> reflect.String:</span><br><span class="line">                <span class="keyword">if</span> i == <span class="number">0</span> &#123;</span><br><span class="line">                    query = fmt.Sprintf(<span class="string">"%s\"%s\""</span>, query, v.Field(i).String())</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    query = fmt.Sprintf(<span class="string">"%s, \"%s\""</span>, query, v.Field(i).String())</span><br><span class="line">                &#125;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                fmt.Println(<span class="string">"Unsupported type"</span>)</span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        query = fmt.Sprintf(<span class="string">"%s)"</span>, query)</span><br><span class="line">        fmt.Println(query)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    fmt.Println(<span class="string">"unsupported type"</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    o := order&#123;</span><br><span class="line">        ordId:      <span class="number">456</span>,</span><br><span class="line">        customerId: <span class="number">56</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    createQuery(o)</span><br><span class="line"></span><br><span class="line">    e := employee&#123;</span><br><span class="line">        name:    <span class="string">"Naveen"</span>,</span><br><span class="line">        id:      <span class="number">565</span>,</span><br><span class="line">        address: <span class="string">"Coimbatore"</span>,</span><br><span class="line">        salary:  <span class="number">90000</span>,</span><br><span class="line">        country: <span class="string">"India"</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    createQuery(e)</span><br><span class="line">    i := <span class="number">90</span></span><br><span class="line">    createQuery(i)</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在第 22 行，我们首先检查了传来的参数是否是一个结构体。在第 23 行，我们使用了 <code>Name()</code> 方法，从该结构体的 <code>reflect.Type</code> 获取了结构体的名字。接下来一行，我们用 <code>t</code> 来创建查询。</p>
<p>在第 28 行，<code>case 语句</code>检查了当前字段是否为 <code>reflect.Int</code>，如果是的话，我们会取到该字段的值，并使用 <code>Int()</code> 方法转换为 <code>int64</code>。if else 语句用于处理边界情况。请添加日志来理解为什么需要它。在第 34 行，我们用来相同的逻辑来取到 <code>string</code>。</p>
<p>我们还作了额外的检查，以防止 <code>createQuery</code> 函数传入不支持的类型时，程序发生崩溃。程序的其他代码是自解释性的。我建议你在合适的地方添加日志，检查输出，来更好地理解这个程序。</p>
<p>该程序会输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">insert into order values(456, 56)</span><br><span class="line">insert into employee values(&quot;Naveen&quot;, 565, &quot;Coimbatore&quot;, 90000, &quot;India&quot;)</span><br><span class="line">unsupported type</span><br></pre></td></tr></table></figure>

<p>至于向输出的查询中添加字段名，我们把它留给读者作为练习。请尝试着修改程序，打印出以下格式的查询。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into order(ordId, customerId) values(456, 56)</span><br></pre></td></tr></table></figure>

<h2 id="我们应该使用反射吗？"><a href="#我们应该使用反射吗？" class="headerlink" title="我们应该使用反射吗？"></a>我们应该使用反射吗？</h2><p>我们已经展示了反射的实际应用，现在考虑一个很现实的问题。我们应该使用反射吗？我想引用 <code>Rob Pike</code>关于使用反射的格言，来回答这个问题。</p>
<blockquote>
<p>清晰优于聪明。而反射并不是一目了然的。</p>
</blockquote>
<p>反射是 Go 语言中非常强大和高级的概念，我们应该小心谨慎地使用它。使用反射编写清晰和可维护的代码是十分困难的。你应该尽可能避免使用它，只在必须用到它时，才使用反射。</p>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#Go" >
    <span class="tag-code">Go</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/35-%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6/">
        <span class="nav-arrow">← </span>
        
          35-读取文件
        
      </a>
    
    
      <a class="nav-right" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/33-%E5%87%BD%E6%95%B0%E6%98%AF%E4%B8%80%E7%AD%89%E5%85%AC%E6%B0%91%EF%BC%88%E5%A4%B4%E7%AD%89%E5%87%BD%E6%95%B0%EF%BC%89/">
        
          33-函数是一等公民（头等函数）
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#什么是反射？"><span class="toc-nav-text">什么是反射？</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#为何需要检查变量，确定变量的类型？"><span class="toc-nav-text">为何需要检查变量，确定变量的类型？</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#reflect-包"><span class="toc-nav-text">reflect 包</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#reflect-Type-和-reflect-Value"><span class="toc-nav-text">reflect.Type 和 reflect.Value</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#relfect-Kind"><span class="toc-nav-text">relfect.Kind</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#NumField-和-Field-方法"><span class="toc-nav-text">NumField() 和 Field() 方法</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#Int-和-String-方法"><span class="toc-nav-text">Int() 和 String() 方法</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#完整的程序"><span class="toc-nav-text">完整的程序</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#我们应该使用反射吗？"><span class="toc-nav-text">我们应该使用反射吗？</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/go/2-Go语言基础/34-反射/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "34-反射",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>